package dao;

import org.apache.ibatis.session.SqlSession;

import mapper.BookMapper;
import model.Book;
import utils.MyBatisUtils;

public class BookDao {
	
	public Book[] findAll() {
		SqlSession session=MyBatisUtils.getSqlSession();
		BookMapper mapper=session.getMapper(BookMapper.class);
		Book[] obj=mapper.findAll();
		session.close();
		return obj;
	}
	
	public Book[] search(String name) {
		SqlSession session=MyBatisUtils.getSqlSession();
		BookMapper mapper=session.getMapper(BookMapper.class);
		Book[] obj=mapper.search(name);
		session.close();
		return obj;
	}
	
	public Book find(String id) {
		SqlSession session=MyBatisUtils.getSqlSession();
		BookMapper mapper=session.getMapper(BookMapper.class);
		Book obj=mapper.find(id);
		session.close();
		return obj;
	}
	
	public String findNewId() {
		SqlSession session=MyBatisUtils.getSqlSession();
		BookMapper mapper=session.getMapper(BookMapper.class);
		String id=mapper.findLastId();
		int a=Integer.parseInt(id.split("b")[1]);
		String newId=Integer.toString(a+1);
		while(newId.length()<6) {
			newId="0"+newId;
		}
		newId="b"+newId;
		return newId;
	};
	
	public void insert(Book obj) {
		SqlSession session=MyBatisUtils.getSqlSessionAutoCommit();
		BookMapper mapper=session.getMapper(BookMapper.class);
		mapper.insert(obj);
		session.close();
	}
	
	public void update(Book obj) {
		SqlSession session=MyBatisUtils.getSqlSessionAutoCommit();
		BookMapper mapper=session.getMapper(BookMapper.class);
		mapper.update(obj);
		session.close();
	}
	
	public void delete(String id) {
		SqlSession session=MyBatisUtils.getSqlSessionAutoCommit();
		BookMapper mapper=session.getMapper(BookMapper.class);
		mapper.delete(id);
		session.close();
	}
	
}
